package com.zf.rabbitmq.producer.alternate_exchange;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 备份交换机；
 * <p>
 * 当发送的某个交换机的消息无法被路由时（无法找到队列），如果交换机设置了备份交换机，那么就会把无法路由的消息发送到备份交换机。否则丢弃消息
 * <p>
 * 为一个交换机声明 备份交换机，使用 "alternate-exchange"="备份交换机名称" 参数，
 * 备份交换机一般声明为 fanout类型，确保消息能够进入备份交换机绑定的队列中
 */
@Component
public class AlternateExchangeConfig implements InitializingBean {
    public static final String testAlterNormalExchange = "test_alter_normal_exchange";
    public static final String testAlternateExchange = "test_alter_alternate_exchange";
    public static final String testAlterNormalQueue = "test_alter_normal_queue";
    public static final String testAlternateQueue = "test_alter_alternate_queue";
    public static final String testAlterNormalRouteKey = "test_alter_normal_route_key";
    @Autowired
    private AmqpAdmin amqpAdmin;

    @Override
    public void afterPropertiesSet() throws Exception {
        // 声明备份交换机和队列
        Queue alterQueue = QueueBuilder.durable(testAlternateQueue).build();
        Exchange alterExchange = ExchangeBuilder.fanoutExchange(testAlternateExchange).durable(true).build();
        Binding alterBinding = BindingBuilder.bind(alterQueue).to(alterExchange).with("").noargs();
        amqpAdmin.declareQueue(alterQueue);
        amqpAdmin.declareExchange(alterExchange);
        amqpAdmin.declareBinding(alterBinding);

        // 声明正常交换机和队列
        Queue normalQueue = QueueBuilder.durable(testAlterNormalQueue).build();
        Exchange normalExchange = ExchangeBuilder.directExchange(testAlterNormalExchange)
                .durable(true)
                .alternate(testAlternateExchange) // 指定备份交换机
                .build();
        Binding normalBinding = BindingBuilder.bind(normalQueue).to(normalExchange).with(testAlterNormalRouteKey).noargs();
        amqpAdmin.declareQueue(normalQueue);
        amqpAdmin.declareExchange(normalExchange);
        amqpAdmin.declareBinding(normalBinding);
    }
}
